package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.model.entity.ActivityModel;
import com.example.demo.model.entity.LevelModel;
import com.example.demo.service.impl.ActivityService;
import com.example.demo.service.impl.LevelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/level")
public class LevelController {

    @Resource
    LevelService levelService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public LevelModel save(@RequestBody LevelModel model) throws Exception {
        model.setLevelId(UUID.randomUUID().toString());
        model.setCreateTime(System.currentTimeMillis());
        return levelService.save(model);
    }


    @RequestMapping(value = "/{level_id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void delete(@PathVariable(value = "level_id") String levelId) throws Exception {
        levelService.delete(levelId);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getAdPage(@RequestParam(value = "page_size", defaultValue = "10") String pageSize, @RequestParam(value = "page_number", defaultValue = "1") String pageNumber) throws Exception {
        Page<LevelModel> adPage = levelService.getLevelPage(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                return null;
            }
        }, new PageRequest(Integer.valueOf(pageNumber) - 1, Integer.valueOf(pageSize)));

        JSONObject result = new JSONObject();
        result.put("total", adPage.getTotalElements());
        result.put("items", adPage.getContent());
        return result;
    }

}
